/*
 * @Author: MiNine
 * @Date: 2020-09-19 09:29:43
 * @LastEditors: MiNine
 * @LastEditTime: 2020-09-27 15:05:04
 * @Description: 
 */
const {
    InsureProduct
} = require('../models/insureProductModel'); //保险产品模块
const {
    InsureSort
} = require("../models/insureSortModel"); //保险分类模块
const {
    uploadFiles,
    moveFiles,
    removeFiles
} = require("../utils/upload"); //图片上传需要


//拿到单个的保险产品详情
async function getItem(req, res) {
    try {
        let {
            _id
        } = req.body; //通过保险id拿到保险详情返回去
        //populate通过保险分类id拿到保险分类详情：目的是渲染分类名字在页面上
        const productDetails = await InsureProduct.findOne({
            _id
        });
        res.send({
            status: 1,
            message: "查找成功",
            productDetails
        })
    } catch (error) {
        res.send({
            status: 0,
            message: "查找失败",
            error
        })
    }
}

//上传图片（这里是在添加图片了，并没有确认上传，暂存在缓存区）
async function avatarAdd(req, res) {
    const images = uploadFiles({
        path: "./public/temp"
    }); //路径以app.js作为参考
    images(req, res, (erro) => {
        if (erro) {
            console.info("上传失败" + erro)
        } else {
            res.send({
                statue: 1,
                massage: "上传成功",
                data: req.files[0].filename //将图片的路径返回去
            })
        }
    })
}

//新增保险产品
async function addItem(req, res) {
    try {
        let {
            productName,
            productPrice,
            compensation,
            uptime,
            belongInsureSortId,
            indate,
            imgSrc,
            productIntroduce
        } = req.body; //拿到新增的整个对象
        //前台传来的格式不对，做截取处理
        let splited = uptime.split("T")[0];
        const obj = {
            productName,
            productPrice,
            compensation,
            uptime: splited,
            belongInsureSortId,
            indate,
            imgSrc,
            productIntroduce
        };
        //判断保险产品存在与否
        const isExisted = await InsureProduct.find({
            productName
        });
        if (isExisted.length > 0) { //存在
            res.send({
                status: 0,
                message: "产品已存在"
            })
        } else { //不存在就将保险产品存进去 
            if (imgSrc) { //判断头像存在与否，存在将缓存区的图片放在图片路径中,且将缓存区的文件夹删除
                moveFiles({
                    fromPath: "./public/temp",
                    toPath: "./public/images",
                    filename: imgSrc
                });
                removeFiles("./public/temp");
            }
            const productAdd = await InsureProduct.create(obj);
            //同时将保险产品的id拿出来存在保险分类里
            const addId = productAdd["_id"]; //新增的产品id
            await InsureSort.updateOne({
                _id: belongInsureSortId
            }, {
                $push: {
                    includeProductList: addId
                }
            });
            res.send({
                status: 1,
                message: "新增成功",
                productAdd
            });
        }
    } catch (error) {
        res.send({
            status: 0,
            message: "新增失败",
            error
        })
    }
}

//删除保险产品
async function delItem(req, res) {
    try {
        let {
            _id
        } = req.body; //通过保险id拿到保险详情返回去
        //populate通过保险分类id拿到保险分类详情：目的是渲染分类名字在页面上
        const productDetails = await InsureProduct.findOne({
            _id
        }).populate("belongInsureSortId");
        const {
            belongInsureSortId
        } = productDetails; //所属的分类的id
        const {
            includeProductList
        } = belongInsureSortId; //获取所属分类所有产品，includeProductList是个数组
        const newArr = includeProductList.filter(item => item != _id); //将不含当前删除产品的id返回来
        const deleteProduct = await InsureProduct.deleteOne({
            _id
        }); //删除指定id的产品
        const deleteSort = await InsureSort.updateOne({
            _id: belongInsureSortId
        }, {
            includeProductList: newArr
        }) //删除分类中的自己
        res.send({
            status: 1,
            message: "删除成功",
            deleteProduct,
            deleteSort
        });
    } catch (error) {
        res.send({
            status: 0,
            message: "删除失败",
            error
        })
    }
}

//修改保险产品信息
async function modItem(req, res) {
    try {
        //只传自己修改的值，这里都列举了，写的时候将不修改的值删掉，图片不能修改
        let {
            _id,
            productName,
            productPrice,
            compensation,
            uptime,
            belongInsureSortId,
            indate,
            productIntroduce
        } = req.body; //通过保险id拿到保险详情返回去
        let splited = uptime.split("T")[0];
        //通过id获取要修改的产品，目的是为了拿到之前分类的id
        const beforeProduct = await InsureProduct.findOne({
            _id
        }).populate("belongInsureSortId");
        //如果新的分类id不等于之前的分类id,那需要将之前分类所属产品数组中将此产品的id删掉，在新分类中将此产品的id上传
        if (beforeProduct.belongInsureSortId != belongInsureSortId) {
            // 删除原本分类中产品 id
            const data = await InsureSort.updateOne({
                _id: beforeProduct.belongInsureSortId
            }, {
                $pull: {
                    includeProductList: _id
                }
            });
            //在新的产品分类中新增产品id
            if (data.ok) {
                const data = await InsureSort.updateOne({
                    _id: belongInsureSortId
                }, {
                    $push: {
                        includeProductList: _id
                    }
                })
                if (data.ok) {
                    var productDetails = await InsureProduct.updateOne({
                        _id
                    }, {
                        productName,
                        productPrice,
                        compensation,
                        uptime: splited,
                        belongInsureSortId,
                        indate,
                        productIntroduce
                    });
                }
            }
        } else { //分两类没有做修改的话，直接更新
            var productDetails = await InsureProduct.updateOne({
                _id
            }, {
                productName,
                productPrice,
                compensation,
                uptime: splited,
                belongInsureSortId,
                indate,
                productIntroduce
            });
        }
        if (productDetails.ok == 1) {
            res.send({
                status: 1,
                message: "修改成功"
            });
        } else {
            res.send({
                status: 0,
                message: "修改失败"
            });
        }
    } catch (error) {
        res.send({
            status: 0,
            message: "修改失败",
            error
        })
    }
}

//返回所有产品
async function getItems(req, res) {
    try {
        let {
            currentPage = 1, pageSize = 5
        } = req.body;
        //总条数多少个 
        const total = await InsureProduct.countDocuments();
        //总页数
        const totalPage = Math.ceil(total / pageSize); //总条数除以每条显示多少条
        const products = await InsureProduct.find().
        limit(pageSize - 0).
        skip((currentPage - 1) * pageSize).
        populate("belongInsureSortId");
        //将状态，以及所有产品返回回去
        res.send({
            status: 1,
            message: "查找成功",
            data: {
                currentPage,
                pageSize,
                total,
                totalPage,
                products
            }
        });
    } catch (error) {
        res.send({
            status: 0,
            message: "查找失败",
            error
        })
    }


    async function getAllItems(req, res) {
        try {
            let products = await InsureProduct.find()
            res.send({
                status: 1,
                message: "查找成功",
                products
            })
        } catch (error) {
            res.send({
                status: 0,
                message: "查找失败",
                error
            })
        }
    }
}

async function getAllItems(req, res) {
    try {
        let products = await InsureProduct.find()
        res.send({
            status: 1,
            message: "查找成功",
            products
        })
    } catch (error) {
        res.send({
            status: 0,
            message: "查找失败",
            error
        })
    }
}

module.exports = {
    getItem,
    addItem,
    avatarAdd,
    delItem,
    modItem,
    getItems,
    getAllItems
}